import React, { useState, useEffect } from 'react';
import { Table, Spin } from 'antd';
import { Resizable } from 'react-resizable';
import './index.css';

// 封装resizable组件
const ResizeableTitle = props => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

// 滚动加载的表格组件
function InfiniteTable(props) {
  // 取props属性
  const { 
    propsColumns, 
    dataSource, 
    loadding, 
    onScrollEnd, 
    onCellResize 
  } = props;
  const [tableW, settableW] = useState(0);
  const [tableH, settableH] = useState(0);
  const [columns, setColumns] = useState(propsColumns);
  const components = {
    header: {
      cell: ResizeableTitle,
    },
  };
  // 列表头拖动监听
  const handleResize = index => (e, { size }) => {
    const nextColumns = [...columns];
    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width > 200 ? 200 : size.width,
    };
    setColumns(nextColumns);
    onCellResize(nextColumns);
  };

  // 监听table的滚动事件
  const tableOnScrollHandler = async (e) => {
    if (loadding || e.target.scrollTop === 0) {
      return;
    }
    let scrollHeight = e.target.scrollHeight;
    let scrollTop = e.target.scrollTop;
    let toBottom = (scrollHeight - scrollTop) - tableH;

    // 如果离底部距离少于60，则触发onScrollEnd
    if (toBottom < 60) {
      onScrollEnd();
    }
  }

  // 初次渲染则按窗口大小计算表格宽高
  useEffect(() => {
    settableW(document.body.clientWidth - 40);
    settableH(document.body.clientHeight - 120);

    // 窗口大小变化，则重新计算宽高
    window.onresize = function() {
      settableW(document.body.clientWidth - 40);
      settableH(document.body.clientHeight - 120);
    }
  }, [tableW, tableH]);
  
  // columns配置压入onHeaderCell事件监听函数
  const curColumns = columns.map((col, index) => ({
    ...col,
    onHeaderCell: column => ({
      width: column.width,
      onResize: handleResize(index),
    }),
  }));

  return (
    <div 
      className="tableWrap">
      {/* loadding */}
      <div className="pageLoadingMask" style={{
        visibility: loadding ? 'visible' : 'hidden'
      }}>
        <Spin className="pageLoading"/>
      </div>
      {/* table容器 */}
      <div 
        className="scrollWrap"
        onScrollCapture={tableOnScrollHandler}>
        <Table
          rowKey="id"
          bordered 
          components={components}
          scroll={{ x: tableW, y: tableH }}
          pagination={false}
          dataSource={dataSource} 
          columns={curColumns} />
      </div>
    </div>
  );
}

export default InfiniteTable;
